const fs = require('fs');
const jwt = require("jsonwebtoken");

const tokenOptions = {
	secretKey:'adwwa_$#%',
	expiresIn:'3d'
};
//创建token
function createToken(account,password){
	let token = jwt.sign(
		{
			account
		},
		tokenOptions.secretKey,
		{
			expiresIn: tokenOptions.expiresIn
		}
	);
	return token;
}

function GetAccount(){
	let result = fs.readFileSync('./data/requiredJSON/account.json');
	result = JSON.parse(result.toString());
	return result;
}
exports.verify = async ctx=>{
	let {token} = ctx.query;
	try{
		let decodeToken = jwt.verify(token,tokenOptions.secretKey);
		ctx.body = {
			status:true
		}
	}catch(e){
		ctx.body = {
			status:false,
			msg:"token已失效"
		}
	}
};
exports.login = async ctx=>{
	let {account,password} = ctx.request.body;
	let result = GetAccount();
	if(result.account===account&&result.password===password){
		let token = createToken(account,password);
		ctx.body = {
			status:true,
			token
		}
	}else{
		ctx.boyd = {
			status:false
		}
	}
};
exports.changePassword = async ctx=>{
	let {oldPassword,newPassword} = ctx.request.body;
	let result = GetAccount();
	if(result.password===oldPassword){
		let data = {
			account:'17637630718',
			password:newPassword
		};
		fs.writeFileSync('./data/requiredJSON/account.json',JSON.stringify(data));
		ctx.body = {
			message: '修改成功!'
		}
	}else{
		ctx.body = {
			message:'旧密码错误!'
		}
	}
};
